package com.changyinBus.web.controller.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.changyinBus.common.utils.StringUtils;
import com.changyinBus.web.controller.bean.UrlSchemeRequest;
import com.changyinBus.web.controller.service.WeChatJsApiService;
import com.changyinBus.web.controller.service.WeChatMiniProgramService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatMiniProgramServiceImpl implements WeChatMiniProgramService {
    @Value("${wechat.open.appId}")
    private String appId;

    @Resource
    private WeChatJsApiService jsApiService;

    @Override
    public Map<String, String> generateMiniProgramConfig(String path) {
        Map<String, String> config = new HashMap<>();
        config.put("appId", appId);
        config.put("originalId", "gh_e1093822fbd7");
        config.put("path", path);
        config.put("timestamp", String.valueOf(System.currentTimeMillis()));
        return config;
    }

    /**
     * 生成URL Scheme
     */
    public String generateUrlLink(UrlSchemeRequest request) {
        String accessToken = null;
        try {
            accessToken = jsApiService.getAccessToken();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("accessToken:"+accessToken);
        String url = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + accessToken;

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("path", request.getPath());
        if (StringUtils.hasText(request.getQuery())) {
            requestBody.put("query", request.getQuery());
        }
        requestBody.put("env_version", "release");
        requestBody.put("expire_type", 0); // 永久有效
        System.out.println("requestBody:"+JSONUtil.toJsonStr(requestBody));
        String response = HttpUtil.post(url, JSONUtil.toJsonStr(requestBody));
        JSONObject json = JSONUtil.parseObj(response);
        System.out.println("response:"+response);
        if (json.getInt("errcode") == 0) {
            return json.getStr("url_link");
        } else {
            throw new RuntimeException("生成URL Link失败: " + json.getStr("errmsg"));
        }
    }
}
